<template>
  <!-- <div>品牌管理</div> -->
  <el-card class="box-card">
    <!-- 顶部添加按钮 -->
    <el-button type="primary" size="default" @click="addTrademark" icon="Plus">
      添加品牌
    </el-button>
    <!-- 表格组件 展示内容 -->
    <el-table border stripe style="margin: 10px 0" :data="trademarkArr">
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="height: 50px; width: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #="{ row, $index }">
          <el-button
            type="warning"
            size="small"
            @click="updateTrademark(row)"
            icon="Edit"
          ></el-button>
          <el-popconfirm
            :title="`确定删除${row.tmName}吗?`"
            @confirm="deleteTrademark(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      :background="true"
      layout="  prev, pager, next, jumper,->,sizes, total"
      :total="total"
      :pager-count="9"
      @current-change="changePageNo"
      @size-change="changeSize"
    />
  </el-card>
  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    width="500"
  >
    <el-form style="width: 80%" :model="trademarkParams" :rules="rules">
      <el-form-item label="品牌名称" label-width="80px" prop="tmName">
        <el-input
          placeholder="请输入品牌名称"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :before-upload="beforeAvatarUpload"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 具名插槽 -->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  reqHasTrademark,
  reqAddorUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark/index.ts'
import type { Trademark } from '@/api/product/trademark/type.ts'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
let pageNo = ref<number>(1)
let pageSize = ref<number>(3)
let total = ref<number>(0)
let trademarkArr = ref([])
let dialogFormVisible = ref<boolean>(false) //控制对话框显示
let trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
})
let formRef = ref()
const validatorTmName = (rule: any, value: any, callback: any) => {
  console.log(123)

  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称应不小于两位'))
  }
}
// const validatorlogoUrl = (rule: any, value: any, callback: any) => {
//     if (value) {
//         callback()
//     } else {
//         callback(new Error('请上传LOGO图片'))
//     }
// }
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  // logoUrl: [
  //     { required: true, validator: validatorlogoUrl }
  // ]
}

const getHasTrademark = async (pager = 1) => {
  let res = await reqHasTrademark(pageNo.value, pageSize.value)
  if (res.code == 200) {
    total.value = res.data.total
    trademarkArr.value = res.data.records
  }
}
onMounted(() => {
  getHasTrademark()
})
const changePageNo = () => {
  getHasTrademark()
}
const changeSize = () => {
  getHasTrademark()
}
const addTrademark = () => {
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
  trademarkParams.id = 0
  dialogFormVisible.value = true
}
const updateTrademark = (row: any) => {
  trademarkParams.logoUrl = row.logoUrl
  trademarkParams.tmName = row.tmName
  trademarkParams.id = row.id
  dialogFormVisible.value = true
}
const cancel = () => {
  dialogFormVisible.value = false
}
const confirm = async () => {
  // await formRef.value.validate()
  let res = await reqAddorUpdateTrademark(trademarkParams)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改成功' : '添加品牌成功',
    })

    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改失败' : '添加品牌失败',
    })
  }
  dialogFormVisible.value = false
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('照片应为 JPG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不可超过 2MB!')
    return false
  }
  return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  trademarkParams.logoUrl = response.data
}
const deleteTrademark = async (id: number) => {
  let res = await reqDeleteTrademark(id)
  // console.log(res);
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasTrademark()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
